package com.itheima.mobilesafe69.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
	public static String encoder(String psd) {
		try {
//				psd = psd+"abcdefghi";//保存密码的时候要去加盐,检测md5码的是不需要加盐
			//1,明确加密算法,getInstance单例模式
			MessageDigest digest = MessageDigest.getInstance("MD5");
			//2,将密码字符进行哈希(随机打乱)操作
			byte[] bs = digest.digest(psd.getBytes());
			System.out.println("bs.length = "+bs.length);
			//3,循环遍历过程,将长度为16的数组中的每一个byte都转换成2位的字符串
			StringBuffer sb = new StringBuffer();
			for (byte b : bs) {
				//4,和0xff做与操作,取其后8位
				int i = b & 0xff;
				//(0-255)(0X0-0XFF)
				//5,将i转换成16进制数
				String hexString = Integer.toHexString(i);
				
				if(hexString.length()<2){
					hexString = "0"+hexString;
				}
				System.out.println(hexString);
				sb.append(hexString);
			}
			System.out.println("转换成的MD5 = "+sb.toString());
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
}
